import router from '@/router';
import NProgress from "@/utils/nprogress";
import { useUserStoreHook, usePermissionStore } from '@/store';
import { RouteRecordRaw } from 'vue-router';
import { TOKEN_KEY } from '@/enums/CacheEnum';

export function setupPermission() {
    // 白名单路由
    const whiteList = ['/login', '/404', '/401'];
    // 路由守卫
    router.beforeEach(async (to, from, next) => {
        NProgress.start();
        const hasToken = localStorage.getItem(TOKEN_KEY);
        if(hasToken) {

            if(to.path === '/login') {
                // 如果已经登录，跳转首页
                next({ path: '/' });
                NProgress.done();
            } else {
                const userStore = useUserStoreHook();
                const hasRoles = userStore.user.roles && userStore.user.roles.length > 0;
                if(hasRoles) {
                    // 未匹配到任何路径
                    if(to.matched.length === 0) {
                        from.name ? next({ name: from.name }) : next('/404');
                    } else {
                        // 已经匹配到路由
                        next();
                    }
                } else {
                    const permissionStore = usePermissionStore();
                    try {
                        const { roles } = await userStore.getUserInfo();
                        const accessRoutes = await permissionStore.generateRoutes(roles);
                        accessRoutes.forEach((route: RouteRecordRaw) => {
                            router.addRoute(route);
                        });
                        next({ ...to, replace: true });
                    } catch(error) {
                        // 移除 token 并跳登录页
                        await userStore.resetToken();
                        next(`/login?redirect=${to.path}`);
                        NProgress.done();
                    }
                }

            }
            
        } else {
            // 未登录，可以访问白名单
            if(whiteList.indexOf(to.path) !== -1) {
                next();
            } else {
                next(`/login?redirect=${to.path}`);
                NProgress.done();
            }
        }
    })

    
    router.afterEach(() => {
        NProgress.done();
    })
}

